import Vue from 'vue'
import Vuex from 'vuex'
import cart from './modules/cart'
import dashboard from './modules/dashboard'
import createPersistencePlugin from './plugins/persistence'
import createLoggerPlugin from './plugins/logger'
import createPerformancePlugin from './plugins/performance'

Vue.use(Vuex)

// 配置插件
const persistencePlugin = createPersistencePlugin({
    storageKey: 'vuex-learning-state',
    reducer: state => ({
        // 只持久化部分状态
        count: state.count,
        user: state.user,
        cart: {
            items: state.cart.items,
            checkoutStatus: state.cart.checkoutStatus
        }
    })
})

const loggerPlugin = createLoggerPlugin({
    collapsed: true,
    filter: (mutation) => {
        // 过滤掉高频更新的mutations
        return !['dashboard/UPDATE_METRICS'].includes(mutation.type)
    }
})

const performancePlugin = createPerformancePlugin({
    threshold: 10, // 10ms为慢操作阈值
    onSlowOperation: (record) => {
        if (record.duration > 50) { // 超过50ms记录为严重性能问题
            console.error('🚨 严重性能问题:', record)
        }
    }
})

// 根据环境决定启用哪些插件
const plugins = []
if (process.env.NODE_ENV === 'development') {
    plugins.push(loggerPlugin, performancePlugin)
}
plugins.push(persistencePlugin) // 持久化插件在所有环境都启用

export default new Vuex.Store({
    // 全局状态
    state: {
        // 计数器状态
        count: 0,
        // 用户信息
        user: {
            name: '',
            email: '',
            isLoggedIn: false
        },
        // Todo列表
        todos: [
            { id: 1, text: '学习Vue基础', done: true },
            { id: 2, text: '学习Vuex状态管理', done: false },
            { id: 3, text: '练习组件通信', done: false }
        ],
        // 加载状态
        loading: false
    },
    
    // 同步更改状态的方法
    mutations: {
        // 计数器相关mutations
        INCREMENT(state) {
            state.count++
        },
        DECREMENT(state) {
            state.count--
        },
        SET_COUNT(state, value) {
            state.count = value
        },
        
        // 用户相关mutations
        SET_USER(state, user) {
            state.user = { ...state.user, ...user }
        },
        LOGIN_SUCCESS(state, user) {
            state.user = {
                name: user.name,
                email: user.email,
                isLoggedIn: true
            }
        },
        LOGOUT(state) {
            state.user = {
                name: '',
                email: '',
                isLoggedIn: false
            }
        },
        
        // Todo相关mutations
        ADD_TODO(state, todo) {
            state.todos.push({
                id: Date.now(),
                text: todo.text,
                done: false
            })
        },
        TOGGLE_TODO(state, id) {
            const todo = state.todos.find(t => t.id === id)
            if (todo) {
                todo.done = !todo.done
            }
        },
        DELETE_TODO(state, id) {
            const index = state.todos.findIndex(t => t.id === id)
            if (index > -1) {
                state.todos.splice(index, 1)
            }
        },
        
        // 加载状态
        SET_LOADING(state, status) {
            state.loading = status
        }
    },
    
    // 异步操作和复杂逻辑
    actions: {
        // 计数器相关actions
        increment({ commit }) {
            commit('INCREMENT')
        },
        decrement({ commit }) {
            commit('DECREMENT')
        },
        incrementAsync({ commit }) {
            return new Promise(resolve => {
                setTimeout(() => {
                    commit('INCREMENT')
                    resolve()
                }, 1000)
            })
        },
        
        // 用户相关actions（模拟异步登录）
        async login({ commit }, credentials) {
            commit('SET_LOADING', true)
            try {
                // 模拟API请求
                await new Promise(resolve => setTimeout(resolve, 1500))
                
                // 模拟登录验证
                if (credentials.email === 'admin@test.com' && credentials.password === '123456') {
                    const user = {
                        name: 'Admin User',
                        email: credentials.email
                    }
                    commit('LOGIN_SUCCESS', user)
                    return { success: true, message: '登录成功！' }
                } else {
                    throw new Error('邮箱或密码错误')
                }
            } catch (error) {
                return { success: false, message: error.message }
            } finally {
                commit('SET_LOADING', false)
            }
        },
        
        logout({ commit }) {
            commit('LOGOUT')
        },
        
        // Todo相关actions
        addTodo({ commit }, todoText) {
            if (todoText.trim()) {
                commit('ADD_TODO', { text: todoText.trim() })
            }
        },
        
        toggleTodo({ commit }, id) {
            commit('TOGGLE_TODO', id)
        },
        
        deleteTodo({ commit }, id) {
            commit('DELETE_TODO', id)
        },
        
        // 批量操作示例
        clearCompletedTodos({ state, commit }) {
            const completedIds = state.todos
                .filter(todo => todo.done)
                .map(todo => todo.id)
            
            completedIds.forEach(id => {
                commit('DELETE_TODO', id)
            })
        }
    },
    
    // 计算属性，基于state计算衍生数据
    getters: {
        // 计数器相关getters
        doubleCount: state => state.count * 2,
        countIsEven: state => state.count % 2 === 0,
        
        // 用户相关getters
        userDisplayName: state => {
            return state.user.isLoggedIn 
                ? `欢迎，${state.user.name}！` 
                : '请登录'
        },
        
        // Todo相关getters
        completedTodos: state => {
            return state.todos.filter(todo => todo.done)
        },
        pendingTodos: state => {
            return state.todos.filter(todo => !todo.done)
        },
        todoStats: (state, getters) => {
            return {
                total: state.todos.length,
                completed: getters.completedTodos.length,
                pending: getters.pendingTodos.length,
                completionRate: state.todos.length > 0 
                    ? Math.round((getters.completedTodos.length / state.todos.length) * 100)
                    : 0
            }
        },
        
        // 根据参数过滤的getter示例
        getTodoById: state => id => {
            return state.todos.find(todo => todo.id === id)
        }
    },
    
    // 模块化管理
    modules: {
        cart,      // 购物车模块
        dashboard  // 实时数据监控模块
    },
    
    // 插件配置
    plugins
})
